package com.microservice.base.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description 主数据库配置(xy - ms - hikcommon)
 * @Author wangzhongxiao
 * @Date: 2020/4/27 16:06
 */
@Configuration
@MapperScan(basePackages = "com.microservice.base.mapper.hikcommon", sqlSessionTemplateRef = "syncSqlSessionTemplate")
public class DataSourceSyncConfig {

    @Bean(name = "syncDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikcommon")
    @Primary
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "syncSqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("syncDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/hikcommon/*.xml"));
        return bean.getObject();
    }


    @Bean(name = "syncTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("syncDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean(name = "syncSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("syncSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}